package org.simplesocket.simplenettycore.handlers;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.simplesocket.simplenettycore.protocol.SimpleProtocol;
import org.simplesocket.simplenettycore.session.ChannelAttr;

import java.nio.charset.StandardCharsets;

class ProtocolDataWriter {
    
    public static void writeDataBack(ChannelHandlerContext ctx, SimpleProtocol sp){
        String sessionID = ctx.channel().attr(ChannelAttr.CLIENT_SESSION_CONTEXT).get().getSessionID();
        ByteBuf buffer = ctx.alloc().buffer();
        
        String body = sp.getData();
        String uri = sp.getUri();
        
        byte[] uriBytes = uri.getBytes(StandardCharsets.UTF_8);
        byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);// 获取数据长度
        
        buffer.writeInt(SimpleProtocol.getProtocolTotalLength(uriBytes,bodyBytes));// 写入长度
        buffer.writeInt(SimpleProtocol.MAGIC_NUMBER);// 写入魔数
        buffer.writeByte(sp.getType().getValue());// 写入类型
        buffer.writeByte(sp.getStatus().getValue());// 写入状态
        buffer.writeBytes(sessionID.getBytes(StandardCharsets.UTF_8));// 写入客户端唯一值
        buffer.writeInt(uriBytes.length);// 写入uri长度
        buffer.writeBytes(uriBytes);// 写入uri
        buffer.writeBytes(bodyBytes);// 写入数据
        ctx.writeAndFlush(buffer);
        
        sp.recycle();// 释放资源
    }
    
}
